package com.tsj.spzx.gateway.filter;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.tsj.spzx.model.entity.user.UserInfo;
import com.tsj.spzx.model.vo.common.Result;
import com.tsj.spzx.model.vo.common.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 先加载 过滤器 ， 然后加载拦截器
 * 在这里：
 *  我们用过滤器拦截请求，判断用户是否登录
 *  在拦截器中拦截，获取用户信息存入ThreadLocal
 */

@Component
public class AuthGlobalFilter implements GlobalFilter {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    /**
     * 获取到当前请求路径，然后进行匹配，如果匹配到，则进行拦截，然后进行登录验证
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取到请求路径
        String path = exchange.getRequest().getURI().getPath();
        if(antPathMatcher.match("/api/**/auth/**",path)){
            // 路径匹配，则要验证是否登录
            UserInfo userInfo = getUserInfo(exchange.getRequest().getHeaders().get("token"));
            if(userInfo == null){
                // 登录失败
                return out(exchange.getResponse(),ResultCodeEnum.LOGIN_AUTH);
            }
        }
        // 存在用户信息，则表示登录，放行
        return chain.filter(exchange);
    }

    /**
     * 根据token获取用户信息
     * @param tokenList exchange.getRequest().getHeaders().get("token") 获取到的是列表
     * @return
     */
    private UserInfo getUserInfo(List<String> tokenList) {
        String token = "";
        if (!CollectionUtil.isEmpty(tokenList)){
            token = tokenList.get(0);
        }
        if (StringUtils.hasText(token)){
            String JsonUserInfo = redisTemplate.opsForValue().get(token);
            if (StringUtils.hasText(JsonUserInfo)){
                return JSONObject.parseObject(JsonUserInfo,UserInfo.class);
            }
        }
        return null;
    }

    /**
     * 用于返回
     * @param response
     * @param resultCodeEnum
     * @return
     */
    private Mono<Void> out(ServerHttpResponse response, ResultCodeEnum resultCodeEnum) {
        Result result = Result.build(null, resultCodeEnum);
        byte[] bits = JSONObject.toJSONString(result).getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }

}
